<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-input v-model="search.mobile" placeholder="手机号码" class="handle-input" width="55"></el-input>
        <el-select class="handle-input" v-model="search.superMember" placeholder="用户等级" @change="changeType(search)" clearable>
          <el-option v-for="item in superMemberList" :key="item.id" :label="item.memberName" :value="item.id" />
        </el-select>
        <el-select class="handle-input" v-model="search.member" placeholder="团队等级" @change="changeType(search)" clearable>
          <el-option v-for="item in memberList" :key="item.id" :label="item.teamName" :value="item.id" />
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="getData()">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-friendadd" @click="showAddUser = true">添加用户 </el-button>
        <!-- <el-button type="primary" @click="freeze">冻结/解冻</el-button> -->
      </div>
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header" @selection-change="handleSelectionChange" @select-all="handleSelectionChange">
        <el-table-column prop="nickname" label="登录账号"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="inviteCode" label="邀请码" align="center"></el-table-column>
        <el-table-column label="合伙人等级" align="center"> <template #default="scope"><el-tag>{{ scope.row.isMemberName }}</el-tag></template> </el-table-column>
        <el-table-column label="团队等级" align="center"> <template #default="scope"><el-tag>{{ scope.row.superMemberName }}</el-tag></template> </el-table-column>
        <el-table-column label="VIP等级" align="center"> <template #default="scope"><el-tag>{{ scope.row.memberName }}</el-tag></template> </el-table-column>
        <el-table-column prop="parentMobile" label="上级登录名"></el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-tag v-if="scope.row.status == '0'">冻结</el-tag>
            <el-tag v-else>未冻结</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册日期" :formatter="dateFormat"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="text" @click="LevelEdit(scope.row)">修改等级</el-button>
            <el-button type="text" @click="cheak_balance(scope.row)">查看资金</el-button>
            <el-button type="text" @click="cheak_performance(scope.row)">查看业绩</el-button>
            <el-button type="text" @click="cheakLowerLevel(scope.row)">查看下级</el-button>
            <el-button type="text" @click="freezeOne(scope.row)">{{ scope.row.status == '0' ? '解冻' : '冻结' }}</el-button>
            <el-button type="text" @click="deleteUser(scope.row)">删除用户</el-button>
            <el-button type="text" @click="edit_node(scope.row)">资金充值</el-button>

            <!-- <el-button type="text" @click="cheak_password(scope.$index, scope.row)">查看密码</el-button> -->
            <!-- <el-button type="text" @click="updateUser(scope.row)">修改用户信息</el-button> -->
            <el-button type="text" @click="editPassword(scope.row)">修改登录密码</el-button>
            <!-- <el-button type="text" @click="editSecondaryPassword(scope.row)">修改二级密码</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex" :page-size="query.pageSize" :total="query.pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 创建用户 -->
    <el-dialog title="创建用户" v-model="showAddUser" width="30%">
      <el-form ref="form" :model="userlist" label-width="70px">
        <el-form-item label="手机号">
          <el-input v-model="userlist.mobile"></el-input>
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="userlist.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邀请码">
          <el-input v-model="userlist.inviteCode"></el-input>
        </el-form-item>
        <el-form-item label="接点人手机号">
          <el-input v-model="userlist.contactMobile"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="userlist.mm"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddUser = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改等级 -->
    <el-dialog title="修改用户等级" v-model="showLevelEdit" width="40%">
      <el-form ref="form" label-width="120px">
        <el-form-item label="合伙人等级">
          <el-select class="mr10" v-model="levelFrom.isMember"> <el-option v-for="item in tierList" :key="item.id" :label="item.tierName" :value="item.id" /> </el-select>
          <el-button type="primary" @click="LevelEditConfirm('tier')">修改</el-button>
        </el-form-item>
        <el-form-item label="团队等级">
          <el-select class="mr10" v-model="levelFrom.superMember"> <el-option v-for="item in teamList" :key="item.id" :label="item.teamName" :value="item.id" /> </el-select>
          <el-button type="primary" @click="LevelEditConfirm('team')">修改</el-button>
        </el-form-item>
        <el-form-item label="VIP等级">
          <el-select class="mr10" v-model="levelFrom.member"> <el-option v-for="item in memberList" :key="item.id" :label="item.memberName" :value="item.id" /> </el-select>
          <el-button type="primary" @click="LevelEditConfirm('member')">修改</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看下级 -->
    <el-dialog title="用户下级" v-model="showLowerLevel" width="40%">
      <el-table :data="LowerLevelList" border class="table" ref="multipleTable" header-cell-class-name="table-header" @selection-change="handleSelectionChange" row-key="id" lazy :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="mobile" label="登录名"></el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showLowerLevel = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户信息 -->
    <el-dialog title="修改用户信息" v-model="showupdateUser" width="30%">
      <el-form ref="form">
        <el-form-item label="合金比例">
          <el-input type="text" v-model="updateUserFrom.customs"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showupdateUser = false">取 消</el-button>
          <el-button type="primary" @click="editUpdateUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户余额 -->
    <el-dialog title="用户余额" v-model="show_node" width="45%">
      <el-form ref="form" :model="form_node" label-width="100px">
        <el-form-item label="选择币种">
          <el-select class="handle-input mr10" v-model="form_node.kindId" placeholder="选择币种"> <el-option v-for="item in kindList" :key="item.id" :label="item.name" :value="item.id" /> </el-select>
        </el-form-item>
        <el-form-item label="交易金额">
          <el-input class="handle-input" v-model="form_node.money" oninput="value=value.replace(/^\.+|[^\d.]/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form_node.status" :disabled="isDisabled">
            <el-radio :label="0">减</el-radio>
            <el-radio :label="1">加</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="show_node = false">取 消</el-button>
          <el-button type="primary" @click="confirm_node">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { api, apiEx } from "../../api/index";
import { formatDate } from "../../common/data";
import moment from "moment";
export default {
  inject: ["reload"],
  filters: {
    formatDate(time) {
      time = time * 1000;
      let date = new Date(time);
      console.log(new Date(time));
      return formatDate(date, "yyyy-MM-dd hh:mm");
    },
  },
  name: "basetable",
  data() {
    return {
      query: {
        pageNo: 1,
        pageTotal: 0,
      },
      tableData: [],
      search: {},
      LowerLevelList: [],
      treeList: [],
      showAddUser: false,
      showupdateUser: false,
      showLowerLevel: false,
      showLevelEdit: false,
      password: "",
      form: {},
      updateUserFrom: {},
      userlist: {},
      show_node: false,
      kindList: [],
      form_node: {
        kindId: '1',
        cyBer: 0
      },

      // 等级相关
      levelFrom: {},
      memberList: [], // VIP等级
      teamList: [], // 团队等级
      tierList: [], // 合伙人等级
    };
  },
  created() {
    this.getData();
    this.getLevelList()
    this.getKindList()
  },
  methods: {
    getLevelList() {
      // VIP等级
      api('/web/usersMemberConfig/select', { parentId: this.$store.state.adminMsg.parentId }).then((res) => { this.memberList = res.data });
      // 团队等级
      api('/web/usersTeamConfig/select', { parentId: this.$store.state.adminMsg.parentId }).then((res) => { this.teamList = res.data });
      // 合伙人等级
      api('/web/usersTierConfig/select', { parentId: this.$store.state.adminMsg.parentId }).then((res) => { this.tierList = res.data });
    },
    // 获取列表数据
    getData() {
      api('/web/capital/subList', {
        limit: 10,
        offset: this.query.pageNo,
        pid: this.$store.state.adminMsg.parentId,
        userId: this.search.userId,
        mobile: this.search.mobile,
        member: this.search.member,
        superMember: this.search.superMember,
      }).then((res) => {
        this.tableData = res.data.rows;
        this.query.pageTotal = res.data.total;
      });
    },

    // 分页导航
    handlePageChange(val) {
      this.query.pageNo = val;
      this.getData();
    },
    // 下拉搜索框
    changeType() {
      this.query.pageNo = 1
      this.getData();
    },

    // 时间过滤器
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    handleSelectionChange(selection) {
      console.log(selection);
      // this.freezeList.push(row.id)
      let list = []
      for (let i = 0; i < selection.length; i++) {
        list.push(selection[i].id);
      }
      this.freezeList = list
    },
    getKindList() {
      api('/web/daKind/s').then((res) => { this.kindList = res.data });
    },

    freeze() {
      this.$confirm("确定要冻结/解冻用户吗？", "提示", { type: "warning" }).then(() => {
        api('/admin/subscribers/subDJ', { id: this.freezeList }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },
    freezeOne(row) {
      this.$confirm("确定要冻结/解冻用户吗？", "提示", { type: "warning" }).then(() => {
        api('/admin/subscribers/subDJ', { id: [row.id] }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },
    deleteUser(row) {
      this.$confirm("该操作用户将不可找回", "确定删除该用户！", { type: "warning" }).then(() => {
        api('/web/capital/d', { userId: row.userId }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },
    setSalesman(row) {
      this.$confirm("注意", "将该用户设置成为中介", {
        type: "warning",
      }).then(() => {
        api('/admin/subscribers/updateLevel', {
          id: row.id,
          isSalesman: 1
        }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            this.reload()
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { });
    },
    //创建用户
    addUser() {
      api('/admin/subscribers/subC', {
        mm: this.userlist.mm,
        mobile: this.userlist.mobile,
        nickname: this.userlist.nickname,
        contactMobile: this.userlist.contactMobile,
        inviteCode: this.userlist.inviteCode,
        parentId: this.$store.state.adminMsg.parentId,
      }).then((res) => {
        if (res.code === 2000) {
          this.$message.success("新增用户成功");
          this.userlist = {};
          this.showAddUser = false;
          this.reload();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    // 查看下级
    cheakLowerLevel(v) {
      this.showLowerLevel = true;
      api('/admin/subscribers/subN', {
        userId: v.userId,
      }).then((res) => {
        this.LowerLevelList = res.data;
      });
    },
    /* 查看下级 -> 树形表格懒加载 */
    load(tree, treeNode, resolve) {
      api('/admin/subscribers/subN', {
        userId: tree.id,
      }).then((res) => {
        this.treeList = res.data;
      });
      setTimeout(() => {
        resolve(this.treeList);
      }, 1000);
    },

    // 查看余额
    cheak_balance(row) {
      api('/web/capital/m', {
        userId: row.userId,
      }).then((res) => {
        this.$alert(`<div>余额：${res.data.a} </div> <div>积分：${res.data.b} </div> <div>贡献值：${res.data.c} </div> <div>贡献总值：${res.data.d} </div> <div>冻结积分：${res.data.e} </div>`, "查看用户余额", { dangerouslyUseHTMLString: true });
      });
    },
    // 查看业绩
    cheak_performance(row) {
      api('/web/capital/a', {
        userId: row.userId,
      }).then((res) => {
        this.$alert(`<div>个人业绩：${res.data.a} </div><div>团队业绩：${res.data.b} </div><div>小区业绩：${res.data.c} </div>`, "查看用户业绩", { dangerouslyUseHTMLString: true });
      });
    },


    // 查看密码
    cheak_password(v) {
      console.log(v);
      this.$alert(
        `<div>用户密码：${v.password} </div>`,
        "查看用户密码", { dangerouslyUseHTMLString: true }
      );
    },

    // 显示修改等级模块
    LevelEdit(v) {
      this.showLevelEdit = true;
      this.levelFrom = v;
    },
    // 修改用于等级
    LevelEditConfirm(value) {
      if (value === 'tier') {
        api('/admin/subscribers/updateTierLevel', { id: this.levelFrom.id, isMember: this.levelFrom.isMember }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            setTimeout(() => {
              this.showLevelEdit = false;
              this.getData()
            }, 1000)
          } else {
            this.$message.error(res.message);
          }
        });
      } else if (value === 'team') {
        api('/admin/subscribers/updateTeamLevel', { id: this.levelFrom.id, superMember: this.levelFrom.superMember }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            setTimeout(() => {
              this.showLevelEdit = false;
              this.getData()
            }, 1000)
          } else {
            this.$message.error(res.message);
          }
        });
      } else if (value === 'member') {
        api('/admin/subscribers/updateLevel', { id: this.levelFrom.id, member: this.levelFrom.member }).then((res) => {
          if (res.code === 2000) {
            this.$message.success(res.message);
            setTimeout(() => {
              this.showLevelEdit = false;
              this.getData()
            }, 1000)
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    // 显示修改用户信息
    updateUser(v) {
      this.showupdateUser = true;
      this.updateUserFrom = v;
    },
    // 修改用户信息
    editUpdateUser() {
      api('/admin/subscribers/update', this.updateUserFrom).then((res) => {
        if (res.code === 2000) {
          this.$message.success("修改成功");
          this.getData();
        } else {
          this.$message.error(res.message);
        }
      });
    },

    // 修改用户密码
    editPassword(v) {
      this.$prompt('请输入新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        api('/admin/subscribers/updatePassword', {
          userId: v.userId,
          password: this.getPass(value),
          parentId: this.$store.state.adminMsg.parentId,
        }).then((res) => {
          if (res.code == 2000) {
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },
    // 修改用户密码
    editSecondaryPassword(v) {
      this.$prompt('请输入新二级密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        api('/admin/subscribers/updateSecondaryPassword', {
          userId: v.userId,
          secondaryPassword: this.getPass(value),
          parentId: this.$store.state.adminMsg.parentId,
        }).then((res) => {
          if (res.code == 2000) {
            this.$message.success(res.message);
          } else {
            this.$message.error(res.message);
          }
        });
      })
    },

    exportar(v) {
      this.$confirm('接点伞下业绩导出', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        apiEx('/web/so/sae', {
          userId: v.userId
        }).then((res) => {
          const blob = new Blob([res]); // 创建blob对象
          const fileName = "接点伞下业绩.xlsx";
          const elink = document.createElement("a"); // 创建的标签
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob); // 创建url
          document.body.appendChild(elink); // 把 创建的标签追加到body里
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink); // 移除标签
          this.$message({
            message: "导出成功！！！",
            type: "success",
          });
          this.$refs.multipleTable.clearSelection();
        });
      })
    },
    edit_node(v) {
      this.show_node = true;
      this.form_node = v;
      console.log(this.form_node);
    },
    confirm_node() {
      api('/web/cyBer/add', {
        kindId: this.form_node.kindId,
        money: this.form_node.money,
        status: this.form_node.status,
        user: this.form_node.mobile
      }).then((res) => {
        if (res.code === 2000) {
          this.$message.success(res.message);
          this.form_node = {};
          this.show_node = false;
        } else {
          this.$message.error(res.message);
          this.form_node = {};
        }
      });
    },


    getPass(item) {
      //将password转化为Base64格式
      const Base64 = require("js-base64").Base64;
      const exStr = Base64.encode(item);
      let jse = new this.$jsEncrypt();
      // 加入rsa public key
      jse.setPublicKey(
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChEuUwaHR5OsJ8EM3/8UwJCngMGwufVnAerVGMz6CLg7q9NDn9dUnr83suKZcCHKUpIvzBqJ05vy3zrYGuS1D4cCCIZiZEzN9I1AfllD1fKmcnz1tL56NWZ4HMfhjesAkjxa69Xmh6qYbIFanqHFkqNje+gZ5hDA8Om1/diT/NzwIDAQAB"
      );
      return jse.encrypt(exStr);
    }

  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 250px;
  display: inline-block;
  margin-right: 10px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.mr10 {
  margin-right: 10px;
}
</style>
